<template>
  <div class="box">
    <!-- 搜索 新增 -->
    <div class="searchFor">
      <el-form :inline="true" :model="formInline">
        <el-input
          v-model="formInline.user"
          placeholder="根据用户名搜索"
          clearable
        ></el-input>
        <el-button size="small" @click="submit">清空</el-button>
        <el-button
          size="small"
          type="primary"
          @click="onSubmit(formInline.user)"
          >搜索</el-button
        >
      </el-form>
      <el-button
        icon="el-icon-edit"
        size="small"
        type="success"
        @click="openDrawer('red')"
      >
        新增用户
      </el-button>
    </div>
    <!-- 记录 -->
    <div class="record">
      <i class="el-icon-info"></i>
      <span>共 {{ total }} 条记录</span>
    </div>
    <!-- 记录 -->
    <!-- table 表格数据区域 -->
    <el-table :data="list" style="width: 100%">
      <el-table-column prop="id" label="序号" min-width="80"> </el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="80">
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" min-width="80">
      </el-table-column>
      <el-table-column prop="username" label="用户名" min-width="80">
      </el-table-column>
      <el-table-column
        prop="permission_group_title"
        label="权限组名称"
        min-width="80"
      >
      </el-table-column>
      <el-table-column prop="role" label="角色" width="80"> </el-table-column>
      <el-table-column prop="address" label="操作">
        <template #default="{ row }">
          <div class="actions">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              plain
              @click="openDrawer('edit', row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              plain
              @click="del(row.id)"
            ></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- table 表格数据区域 -->

    <!-- 分页组件区域 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryObj.current"
        :page-size="queryObj.pageSize"
        layout=" prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30, 50]"
        background
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 分页组件区域 -->

    <!-- 弹窗组件 -->
    <el-dialog
      :title="drawerTitle"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      width="50%"
    >
      <span slot="footer" class="dialog-footer">
        <div class="form">
          <el-form :rules="rules" :model="form" ref="form" label-width="90px">
            <el-form-item label="用户名：" prop="username">
              <el-input placeholder="请输入用户名" v-model="form.username" />
            </el-form-item>
            <el-form-item label="邮箱：" prop="email">
              <el-input
                placeholder="请输入邮箱："
                v-model="form.email"
                type="emal"
              />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input
                placeholder="请输入密码："
                v-model="form.password"
                type="password"
              />
            </el-form-item>
            <el-form-item label="角色：" prop="role">
              <el-input
                placeholder="请输入角色："
                v-model="form.role"
                type="role"
              />
            </el-form-item>
            <el-form-item label="权限组名称">
              <el-select
                placeholder="请选择"
                v-model="form.permission_group_id"
              >
                <el-option
                  :label="item.permission_group_id"
                  :value="item.permission_group_id"
                  v-for="item in list"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话：" prop="mobile">
              <el-input
                placeholder="请输入联系电话："
                v-model="form.mobile"
                type="phone"
              />
            </el-form-item>
            <el-form-item label="介绍">
              <el-input type="textarea" placeholder="Please input"></el-input>
            </el-form-item>
          </el-form>
          <div class="button">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="increaseAdd">确 定</el-button>
          </div>
        </div>
      </span>
    </el-dialog>
    <!-- 弹窗组件 -->
  </div>
</template>

<script>
import { list, remove, update, detail, add } from '@/api/base/users.js'

export default {
  data () {
    return {
      // tableData: {
      //   id: '',
      //   email: '',
      //   phone: '',
      //   username: '',
      //   permission_group_title: '', // 权限组名称
      //   role: ''
      // },
      formInline: {
        user: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
      },
      form: {
        avatar: '',
        email: '', // 邮件
        introduction: '',
        password: '123456',
        permission_group_id: null,
        phone: '', // 联系电话
        role: '', // 角色
        username: '' // 姓名
      },
      queryObj: {
        current: 1, // 控制当前页
        pageSize: 10 // 控制每一页有几条数据
      },
      dialogVisible: false, // 打开添加
      drawerType: 'red',
      total: 0, // 总记录数
      list: [],
      id: 0
    }
  },

  created () {
    this.initTable()
  },

  methods: {
    // 获取table数据
    async initTable () {
      const { data } = await list()
      console.log(data)

      this.list = data.list
      this.total = data.counts
      console.log(this.list)
    },
    // 点击删除图标删除对应的数据
    async del (id) {
      console.log(id)
      try {
        await remove(id)
        this.$message.success('删除成功')
        this.initTable()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    // pageSize 改变时会触发
    handleSizeChange (pagesize) {
      // console.log(`每页 ${val} 条`)
      this.queryObj.pageSize = pagesize

      this.initTable()
    },

    // current当前页改变时会触发
    handleCurrentChange (page) {
      // console.log(`当前页: ${val}`)
      // 改变参数对象中的当前页
      this.queryObj.current = page
      this.initTable()
    },
    // 打开添加组件
    async openDrawer (type, id) {
      this.drawerType = type

      // 编辑修改功能
      if (type !== 'red') {
        const { data } = await detail(id)

        console.log(data)

        this.form = data
        this.id = data.id
      }
      this.dialogVisible = true
    },
    // 添加组件关闭之前触发
    handleClose () {
      // 清空表单
      this.form = ''

      // 重置表单
      if (this.drawerType !== 'preview') {
        // red edit 调用 resetFields 在此处的作用: 重置校验状态
        this.$refs.form.resetFields()
      }

      this.dialogVisible = false
    },
    // 添加用户功能
    async increaseAdd () {
      // 表单的非空验证
      try {
        await this.$refs.form.validate()

        await add(this.form)
        if (this.drawerType === 'red') {
          // 发起添加请求await
          await add(this.form)
        }
        if (this.drawerType === 'edit') {
          await update({ id: this.id, ...this.form })
          console.log(1)
        }

        // 清空表单
        this.form = ''
        // 关闭抽屉组件
        this.dialogVisible = false

        // 提示用户
        this.$message.success(
          this.drawerType === 'red' ? '添加成功' : '修改成功'
        )

        // 重新获取新的数据渲染页面
        this.initTable()
      } catch (error) {
        this.$message.error('请输入必填项')
      }
    },
    // 清空搜索
    submit () {
      this.formInline.user = ''
      this.initTable()
    },
    // 搜索
    onSubmit (user) {
      console.log(this.list.username)
      console.log(user)
      this.list = this.list.filter(item => {
        console.log(item.username)
        return item.username === user
      })
    }
  },
  computed: {
    drawerTitle () {
      if (this.drawerType === 'red') return '添加用户'
      if (this.drawerType === 'edit') return '编辑用户'
      else {
        return 'red'
      }
    }
  }
}
</script>

<style scoped lang="less">
.box {
  padding: 20px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  margin: 20px;
  .searchFor {
    display: flex;
    justify-content: space-between;
    height: 32px;
    .el-form {
      display: flex;
      .el-input {
        width: 200px;
        font-size: 13px;
      }
      .el-button {
        margin-left: 15px;
      }
    }
  }
  .record {
    width: 100%;
    margin: 20px 0;
    background-color: #f4f4f5;
    color: #909399;
    padding: 8px 16px;
    span {
      padding: 0 8px;
      font-size: 13px;
      line-height: 18px;
    }
  }
  .el-table {
    width: 100%;
    ::v-deep .el-table__cell {
      text-align: center;
    }
    ::v-deep .el-table__header-wrapper {
      border-bottom: 2px solid #e8e8e8;
      .hidden-columns {
        background-color: #fafafa;
      }
    }
  }
  .block {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    ::v-deep .el-pagination__jump {
      margin-left: 0;
    }
  }
  .button {
    margin-top: 30px;
    text-align: center;
  }

  ::v-deep .el-dialog__body {
    display: none !important;
  }
  .form {
    width: 350px;
    margin: 30px auto;
  }
}
</style>
